package org.zjvis.datascience.common.widget.vo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.zjvis.datascience.common.vo.PageVO;
import org.zjvis.datascience.common.vo.column.ColumnQueryVO;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * @description 用于图表控件的 统计结果 的分页包装类POJO
 * @date 2021-12-01
 */
@Data
public class WidgetStatRequestVO extends PageVO {

    private Long projectId;

    @NotEmpty(message = "tableName cannot be null")
    private String tableName;

    @NotNull(message = "taskId or datasetId cannot be empty")
    private Long dataId;

    @NotNull(message = "please specify column name")
    private String colName;

    @NotNull(message = "please specify column type")
    private Integer type;

    private String keyword;

    @NotNull(message = "please specify node type, task || dataset")
    private String startNodeType;

    public ColumnQueryVO toColumnQueryVO() {
        ColumnQueryVO vo = new ColumnQueryVO();
        vo.setTaskId(this.dataId);
        vo.setTable(this.tableName);
        vo.setName(this.colName);
        vo.setType(this.type);

        if (this.pageSize != null) {
            vo.setPageSize(this.pageSize);
        }
        if (this.curPage != null) {
            vo.setCurPage(this.curPage);
        }
        vo.setData(new JSONObject());
        vo.setFilter(new JSONArray());
        vo.setMode(1);     //统计模式 1=详情detail 2=摘要abstract
        vo.setSortType(1);     //1=字段序;2=统计序
        vo.setSortVal("ASC");
        vo.setSearchFilter(this.wrapSearchFilter());
        return vo;
    }

    /**
     * 为了复用TcolumnService queryStat方法 拼装需要的SearchFilter 格式
     * @return
     */
    private JSONArray wrapSearchFilter() {
        JSONArray result = new JSONArray();
        if (StringUtils.isNotEmpty(this.keyword)) {
            JSONArray searchFilter = new JSONArray();
            JSONObject searchItem = new JSONObject();
            searchItem.put("col", this.colName);
            searchItem.put("filterType", "like");
            JSONArray values = new JSONArray();
            values.add("%" + this.keyword + "%"); // ε=(´ο｀*)))唉  new String[]{} 不能用
            searchItem.put("values", values);
            searchFilter.add(searchItem);
            result.add(searchFilter);
        }
        return result;
    }

    public boolean isFromTask() {
        return this.getStartNodeType().equals("task");
    }
}
